package com.lsf.studentmanagerup.listener;

import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * 监听request   开始和结束时
 *
 * @author 李树飞
 */
public class MyListener implements ServletRequestListener {
    @Override
    public void requestDestroyed(ServletRequestEvent servletRequestEvent) {

    }

    @Override
    public void requestInitialized(ServletRequestEvent servletRequestEvent) {
        HttpServletRequest httpServletRequest = (HttpServletRequest)servletRequestEvent.getServletRequest();
        HttpSession session = httpServletRequest.getSession();

        if (null == session.getAttribute("user")) {
            //如果没有登录信息，则从cookie中获取
            Cookie[] cookies = httpServletRequest.getCookies();
            System.out.println("检查cookie");
            //遍历是否存在user
            if (null != cookies) {
                for (Cookie cookie : cookies) {
                    if ("user".equalsIgnoreCase(cookie.getName())) {
                        session.setAttribute("user", cookie.getName());
                        System.out.println("成功从cookie导入登录信息到session");
                    }
                }
            }
        }
    }
}
